#! /usr/bin/env python
# -*- coding: iso-8859-1 -*-

# chimera - observatory automation system
# Copyright (C) 2006-2007  P. Henrique Silva <henrique@astro.ufsc.br>

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.


from chimera.core.cli import ChimeraCLI, action, parameter
from chimera.core.callback import callback
from chimera.core.exceptions import ChimeraException
from chimera.core.compat import freeze_support

from chimera.interfaces.pointverify import CantPointScopeException, CanSetScopeButNotThisField, CantSetScopeException, PointVerify
from chimera.util.sextractor import SExtractorException

from chimera.util.ds9 import DS9
from chimera.util.astrometrynet import AstrometryNet

import sys
import time    
import os

class ChimeraPointVerify (ChimeraCLI):
    
    def __init__ (self):
	# are these entities being created or am I referring to existing things?
        # the first entry is how the script will be called
        # the second entry is an English language description of the script
        ChimeraCLI.__init__(self, "chimera-pverify", "Point Verifier", 0.1)
        self.addHelpGroup("PVERIFY", "PVerify")
        self.addController(name="pverify", cls="PointVerify", required=True, helpGroup="PVERIFY", help="Pointing verification controller to be used")
        self.addParameters(dict(name="pverify_file",long="fname",type="string",
                                helpGroup="PVERIFY",help="Does astrometry on file",metavar="FILE"))

    

    # ok, looks like action establishes that the following method is some 
    # action performed by this script    
    @action(long="choose", 
            help="Chooses a field to point the scope to, moves the scope, takes an image and verifies the pointing", 
           helpGroup="PVERIFY")
    def checkPointing (self,options):
        """
        Chooses a field to point the scope to, moves the scope, 
        takes an image and verifies the pointing
        """
        self.out("Choosing a field in the sky, moving scope and taking images")
        try:
            self.pverify.checkPointing()
        except CantSetScopeException, e:
            self.exit("Can't set scope")
        self.out("OK")


    @action(long="file",
	    short="f",
            type="string",
            help="Does astrometry on a specific file" ,
            helpGroup="PVERIFY",
	    metavar="Filename.fits")
    def file(self,options):
        """
        Returns a new image with new WCS
        """
        self.out("Doing astrometry on file : %s \n" %(options.file))
        try:
            AstrometryNet.solveField(options.file,findstarmethod="sex")
        except CantSetScopeException, e:
            self.exit("Can't set scope")
        self.out("OK")
    
    @action(long="list",
	    short="l",
	    type="string",
            help="Does astrometry on a list of files",
	    helpGroup="PVERIFY",
	    metavar="Listfile")
    def list(self, options):

     if options.list != None:
	file = open(options.list, 'r')
	print options.list
        for line in file:
		while line.endswith('\n') or line.endswith('\t') or line.endswith(' '): line = line[0:-1]
		try:
			AstrometryNet.solveField(line, findstarmethod='sex')
		except Exception, e:
			print e


    @action(long="here", short="-A",
            help="Takes an image where telescope is pointed to, tries to find image RA, DEC, and tries to recenter the telescope.", helpGroup="PVERIFY")
    def checkHere(self,options):
        """
        Takes an image where telescope is pointed to, 
        tries to find image RA, DEC, 
        and tries to recenter the telescope
        """
        self.out("Centering scope on current field.")
        try:
            self.pverify.pointVerify()
        except CanSetScopeButNotThisField, e:
            self.out("Error setting on this field specifically; check for coluds or light pollution.")
        self.out("OK")		
        
def main():
    cli = ChimeraPointVerify()
    cli.run(sys.argv)
    cli.wait()
    
if __name__ == '__main__':
    freeze_support()
    main()
